package liuwh.mina.basic.tcp.server.tiemserver.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class TimeResponseDecoder extends CumulativeProtocolDecoder {

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		
		CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();

		int start = in.position();

		int end = in.remaining() - 1;
		
		if (end >= 0 && in.get(end) == (byte) '\n') {
			
			String res = in.getString(decoder);
			out.write(res);
			
			return true;
			
		} else {
			in.position(start);
		}

		return false;
	}

}
